# -*- coding: utf-8 -*-
from PyQt4.QtCore import *
from PyQt4.QtGui import *

from qgis.core import *
from qgis.gui import *

from infomaptool import *
from ui_control import ui_Control
import resources_rc

class TestPlugin:

  def __init__(self, iface):
    self.iface = iface
    self.canvas = iface.mapCanvas()
	
  def canvasMoveEvent(self,event):
    self.emit( SIGNAL("moved"),self.doCoordinate)

  def initGui(self):
    # create action that will start plugin configuration
    self.action = QAction(QIcon(":/icon.png"), "PK Geo", self.iface.mainWindow())
    self.action.setWhatsThis("Testing My first plug-in")
    self.action.setStatusTip("Start it")

    # connect the action to the run method
    QObject.connect(self.action, SIGNAL("activated()"), self.run)

    # add toolbar button and menu item
    self.iface.addToolBarIcon(self.action)
    self.iface.addPluginToMenu("&Test plugin PKGeo", self.action)

    # pass to class
    self.tool = InfoMapTool(self.iface.mapCanvas(),self.action)

  def unload(self):
    # remove the plugin menu item and icon
    self.iface.removePluginMenu("&Test plugin PKGeo",self.action)
    self.iface.removeToolBarIcon(self.action)

  def run(self):
    # create and show a configuration dialog or something similar
    # Load QT GUI--> ui_Control
    flags = Qt.WindowTitleHint | Qt.WindowSystemMenuHint | Qt.WindowMaximizeButtonHint  # QgisGui.ModalDialogFlags
    self.pluginGui = ui_Control(self.iface.mainWindow(), flags)

    #Test Mouse Event
    #QObject.connect(self.iface.mapCanvas(),SIGNAL("rightClicked"),self.doCoordinate)
    QObject.connect(self.tool, SIGNAL("leftClicked"), self.leftClicked)
    self.saveTool = self.canvas.mapTool()
    self.canvas.setMapTool(self.tool)

    #INSERT EVERY SIGNAL CONECTION HERE!
    # Command for Control Handle event
    #btnClose
    QObject.connect(self.pluginGui.btnClose, SIGNAL('clicked()'), self.doClose)
    #btnShowMsgBox
    QObject.connect(self.pluginGui.btnShowMsgBox, SIGNAL('clicked()'),self.doShow)
    #TextEdit
    expText = "Hi my name is Chaipat Nengcomma ,\n" + \
              "This is my first time to develop Qgis Plug-in .\n" + \
              "@2009, September.\n"
    #self.pluginGui.textEdit.setText(expText)
    self.pluginGui.textEdit.setPlainText(expText)
	
    #btnShowCoord
    QObject.connect(self.pluginGui.btnShowCoord, SIGNAL('clicked()'),self.getCoordinate)
    self.pluginGui.show()

  def doClose(self):
    self.pluginGui.reject()

  def doShow(self):
    infoString = QString("Hello, world!")
    QMessageBox.information(self.iface.mainWindow(),"About",infoString)

  def getCoordinate(self):
    mapCanvas = self.iface.mapCanvas()
    for i in range(mapCanvas.layerCount()):
      layer = mapCanvas.layer(i)
      if layer.type() == layer.VectorLayer:
          a=layer.extent()

    #self.pluginGui.textEdit_X.setText(a[0].toString())
    #self.pluginGui.textEdit_Y.setText(a[1].toString())
    QMessageBox.information(self.iface.mainWindow(),"Layer Extent ",a.toString())
    
  def doCoordinate(self,event):
    #self.saveTool = self.canvas.mapTool()
    #{'x': event.pos().x(), 'y': event.pos().y()} 
    self.pluginGui.textEdit_X.setText(event.pos().x())
    self.pluginGui.textEdit_Y.setText(event.pos().y())
    #QMessageBox.information(self.iface.mainWindow(),"Layer Extent ",event.pos().y())

  def leftClicked(self,xy):
	dt = "info-leftClicked"
	mapCoords = self.canvas.getCoordinateTransform().toMapCoordinates(xy["x"],xy["y"])
	#imgCoords = self.canvas.getCoordinateTransform().toMapCoordinates(xy["x"],xy["y"])
	#pixs = QgsMapToPixel(0.00013735,14.079,13.170,100.002)
	# Get Image info
	img_layers = self.iface.mapCanvas().layer(0)
	extlayer = img_layers.extent()
	#extlayer = img_layers.setCrs(QgsCoordinateReferenceSystem()).extent() # non srs
	img_height = img_layers.height()
	img_width = img_layers.width()
	# warp canvas
	self.canvas.setExtent(extlayer)
	cav_pixs = self.canvas.getCoordinateTransform() # canvas dimension
	
	# cal canvas coordinte of image frame
	#c_ul = cav_pixs.transform(extlayer.xMinimum(),extlayer.yMaximum())
	#c_ll = cav_pixs.transform(extlayer.xMinimum(),extlayer.yMinimum())
	#image_frame = QgsMapToPixel(cc,c_ul.y(),c_ll.y(),c_ll.x())
	c_ul = cav_pixs.transform(0,0)
	c_ll = cav_pixs.transform(0,-img_height)
	# cal pixel size
	cc = (c_ul.y()-c_ll.y())/img_height
	#cc = img_layers.rasterUnitsPerPixel()
	# Build image_frame domian from canvas coordinate
	image_frame = QgsMapToPixel(cc,c_ul.y(),c_ll.y(),c_ll.x())
	# find point to image coord
	pix = image_frame.transform(xy["x"],xy["y"])
	
	
	

	
	#old method
	#mupp = (extlayer.yMaximum()-extlayer.yMinimum())/img_height
	#mupp = (extlayer.xMaximum()-extlayer.xMinimum())/img_width
	#pixs = QgsMapToPixel(img_layers.rasterUnitsPerPixel(),extlayer.yMaximum(),extlayer.yMinimum(),extlayer.xMinimum())
	#pix = pixs.transform(mapCoords.x(),mapCoords.y())
	
	#pix = pixs.transform(mapCoords)
	self.pluginGui.textEdit_X.setText(str(mapCoords.x()))
	self.pluginGui.textEdit_Y.setText(str(mapCoords.y()))
	#-----
	#self.pluginGui.textEdit_X.setText(str(xy["x"]))
	#self.pluginGui.textEdit_Y.setText(str(xy["y"]))
	self.pluginGui.textEdit_mX.setText(str(float(pix.x()*-1)))
	self.pluginGui.textEdit_mY.setText(str(float(pix.y()+img_height)*-1))
	#QMessageBox.information(self.iface.mainWindow(),"show ",str(self.canvas.mapUnitsPerPixel()))
    
